<script setup>
import productAPI from '../api/product_api.js'
import categoryAPI from '../api/category_api.js'
import brandAPI from '../api/brand_api.js'
import { ref, onMounted } from "vue";
import {
  ElMessageBox,
  ElPagination,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElPopover,
  ElTag,
  ElUpload,
  ElIcon
} from 'element-plus';
import { Timer } from '@element-plus/icons-vue';
import lodash from 'lodash';

// 表格数据 & 分页数据
const tableData = ref([]);
const total = ref(0);

// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  name: '',
  category_id: '',
  brand_id: ''
});

// 新增/编辑弹窗绑定对象
const obj = ref({});
// 弹窗显隐控制
const editWinVisible = ref(false);
const addWinVisible = ref(false);

// 下拉选项数据
const categories = ref([]);
const brands = ref([]);

// 页面加载时初始化数据
onMounted(async () => {
  await search();
  await loadCategories();
  await loadBrands();
});

// 图片上传成功回调
const handleUploadSuccess = (response, file) => {
  console.log('图片上传成功:', response);
  obj.value.img = response.data;
};

// 通用查询方法
const search = async () => {
  try {
    const result = await productAPI.page(searchObj.value);
    tableData.value = result.data || [];
    total.value = result.count || 0;
  } catch (error) {
    console.error('查询商品失败:', error);
    ElMessageBox.alert('查询商品失败，请稍后重试', '错误', { type: 'error' });
  }
};

// 加载分类下拉列表
const loadCategories = async () => {
  try {
    const result = await categoryAPI.page({ current: 1, limit: 100 });
    categories.value = result.data || [];
  } catch (error) {
    console.error('加载分类失败:', error);
    ElMessageBox.alert('加载分类失败，请稍后重试', '错误', { type: 'error' });
  }
};

// 加载品牌下拉列表
const loadBrands = async () => {
  try {
    const result = await brandAPI.page({ current: 1, limit: 100 });
    brands.value = result.data || [];
  } catch (error) {
    console.error('加载品牌失败:', error);
    ElMessageBox.alert('加载品牌失败，请稍后重试', '错误', { type: 'error' });
  }
};

// 根据ID获取分类名称
const getCategoryName = (id) => {
  if (!id) return '未选择';
  const category = categories.value.find(item => item.id === id);
  return category ? category.name : '未知分类';
};

// 根据ID获取品牌名称
const getBrandName = (id) => {
  if (!id) return '未选择';
  const brand = brands.value.find(item => item.id === id);
  return brand ? brand.name : '未知品牌';
};

// 分页改变事件
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = () => {
  search();
};

// 搜索按钮点击事件
const handlerSearch = async () => {
  searchObj.value.current = 1;
  await search();
};

// 新增弹窗 - 取消
const addCancel = () => {
  obj.value = {};
  addWinVisible.value = false;
};

// 新增弹窗 - 提交
const addCommit = async () => {
  try {
    await productAPI.add(obj.value);
    ElMessageBox.alert('新增商品成功', '成功', { type: 'success' });
    await search();
    addWinVisible.value = false;
    obj.value = {};
  } catch (error) {
    console.error('新增商品失败:', error);
    ElMessageBox.alert('新增商品失败，请稍后重试', '错误', { type: 'error' });
  }
};

// 编辑弹窗 - 取消
const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};

// 编辑弹窗 - 提交
const editCommit = async () => {
  try {
    await productAPI.edit(obj.value);
    ElMessageBox.alert('编辑商品成功', '成功', { type: 'success' });
    await search();
    editWinVisible.value = false;
  } catch (error) {
    console.error('编辑商品失败:', error);
    ElMessageBox.alert('编辑商品失败，请稍后重试', '错误', { type: 'error' });
  }
};

// 打开新增弹窗
const handleAdd = () => {
  obj.value = {};
  addWinVisible.value = true;
};

// 打开编辑弹窗
const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
};

// 删除操作
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该商品吗？此操作不可撤销',
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        try {
          await productAPI.del(row.id);
          ElMessageBox.alert('删除商品成功', '成功', { type: 'success' });
          searchObj.value.current = 1;
          await search();
        } catch (error) {
          console.error('删除商品失败:', error);
          ElMessageBox.alert('删除商品失败，请稍后重试', '错误', { type: 'error' });
        }
      })
      .catch(() => {});
};
</script>

<template>
  <!-- 搜索表单 -->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px ">
    <el-form-item label="商品名称">
      <el-input v-model="searchObj.name" placeholder="请输入商品名称" clearable />
    </el-form-item>

    <!-- 分类下拉搜索 -->
    <el-form-item label="分类">
      <el-select
          v-model="searchObj.category_id"
          placeholder="请选择分类"
          clearable
          style="width: 200px"
      >
        <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </el-form-item>

    <!-- 品牌下拉搜索 -->
    <el-form-item label="品牌">
      <el-select
          v-model="searchObj.brand_id"
          placeholder="请选择品牌"
          clearable
          style="width: 200px"
      >
        <el-option
            v-for="item in brands"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </el-form-item>
  </el-form>

  <!-- 查询、新增按钮 -->
  <el-form :inline="true" style="margin-bottom: 10px;">
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </el-form-item>
  </el-form>

  <!-- 商品表格 -->
  <el-table :data="tableData" style="width: 100%" border>
    <!-- ID 列 -->
    <el-table-column label="ID" width="80" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>id: {{ scope.row.id }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.id }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <!-- 商品名称列 -->
    <el-table-column label="商品名称" width="180" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>名称: {{ scope.row.name }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.name }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <!-- 分类列 -->
    <el-table-column label="分类" width="100" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>分类 ID: {{ scope.row.category_id }}</div>
          </template>
          <template #reference>
            <el-tag>{{ getCategoryName(scope.row.category_id) }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <!-- 品牌列 -->
    <el-table-column label="品牌" width="100" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>品牌 ID: {{ scope.row.brand_id }}</div>
          </template>
          <template #reference>
            <el-tag>{{ getBrandName(scope.row.brand_id) }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <!-- 型号列 -->
    <el-table-column label="型号" width="180" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>型号: {{ scope.row.model }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.model }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <!-- 价格列 -->
    <el-table-column label="价格" width="100" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>价格: {{ scope.row.price }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.price }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <!-- 商品图片列 -->
    <el-table-column label="商品图片" width="120" align="center">
      <template #default="scope">
        <div class="img-preview">
          <img
              :src="scope.row.img || 'https://xrysitu.oss-cn-beijing.aliyuncs.com/a2b619ac-9909-4af9-b75b-5e0fee3b7473.jpg'"
              alt="商品图片"
              class="product-img"
              @error="(e) => e.target.src = 'https://xrysitu.oss-cn-beijing.aliyuncs.com/a2b619ac-9909-4af9-b75b-5e0fee3b7473.jpg'"
          />
        </div>
      </template>
    </el-table-column>

    <!-- 库存数列 -->
    <el-table-column label="库存数" width="100" align="center">
      <template #default="scope">
        <div style="display: flex; align-items: center; justify-content: center">
          <el-icon><timer /></el-icon>
          <span style="margin-left: 10px">{{ scope.row.nums }}</span>
        </div>
      </template>
    </el-table-column>

    <!-- 操作列 -->
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 10px; text-align: right;"
  />

  <!-- 编辑弹窗 -->
  <el-dialog v-model="editWinVisible" title="编辑商品" width="500">
    <el-form :model="obj" label-width="100px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="obj.name" autocomplete="off" />
      </el-form-item>

      <!-- 分类下拉选择 -->
      <el-form-item label="分类" prop="category_id">
        <el-select
            v-model="obj.category_id"
            placeholder="请选择分类"
            style="width: 100%"
        >
          <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 品牌下拉选择 -->
      <el-form-item label="品牌" prop="brand_id">
        <el-select
            v-model="obj.brand_id"
            placeholder="请选择品牌"
            style="width: 100%"
        >
          <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="型号" prop="model">
        <el-input v-model="obj.model" autocomplete="off" />
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input v-model="obj.price" autocomplete="off" />
      </el-form-item>

      <el-form-item label="商品描述" prop="message">
        <el-input v-model="obj.message" type="textarea" rows="3" autocomplete="off" />
      </el-form-item>

      <el-form-item label="商品图片" prop="img">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img
              :src="obj.img ? obj.img : 'https://xrysitu.oss-cn-beijing.aliyuncs.com/a2b619ac-9909-4af9-b75b-5e0fee3b7473.jpg'"
              style="width: 100px; height: 100px; object-fit: cover; border-radius: 4px;"
              alt="商品图片"
          />
        </el-upload>
      </el-form-item>

      <el-form-item label="库存数" prop="nums">
        <el-input v-model="obj.nums" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增弹窗 -->
  <el-dialog v-model="addWinVisible" title="新增商品" width="500">
    <el-form :model="obj" label-width="100px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="obj.name" autocomplete="off" />
      </el-form-item>

      <!-- 分类下拉选择 -->
      <el-form-item label="分类" prop="category_id">
        <el-select
            v-model="obj.category_id"
            placeholder="请选择分类"
            style="width: 100%"
        >
          <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 品牌下拉选择 -->
      <el-form-item label="品牌" prop="brand_id">
        <el-select
            v-model="obj.brand_id"
            placeholder="请选择品牌"
            style="width: 100%"
        >
          <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="型号" prop="model">
        <el-input v-model="obj.model" autocomplete="off" />
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input v-model="obj.price" autocomplete="off" />
      </el-form-item>

      <el-form-item label="商品描述" prop="message">
        <el-input v-model="obj.message" type="textarea" rows="3" autocomplete="off" />
      </el-form-item>

      <el-form-item label="商品图片" prop="img">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img
              :src="obj.img ? obj.img : 'https://picsum.photos/100/100'"
              style="width: 100px; height: 100px; object-fit: cover; border-radius: 4px;"
              alt="商品图片"
          />
        </el-upload>
      </el-form-item>

      <el-form-item label="库存数" prop="nums">
        <el-input v-model="obj.nums" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-table {
  margin-top: 10px;
}

/* 表格中商品图片样式 */
.img-preview {
  width: 80px;
  height: 80px;
  margin: 0 auto;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #eee;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-img:hover {
  transform: scale(1.1);
}

/* 上传组件样式 */
.avatar-uploader {
  cursor: pointer;
  display: inline-block;
}

.avatar-uploader:hover img {
  opacity: 0.8;
}

/* 弹窗表单样式 */
.el-form-item {
  margin-bottom: 15px;
}
</style>
